import { createSlice } from "@reduxjs/toolkit"
// import type { RootState } from "@/store"
// 用户信息类型
import type { UserInfo } from "@/api/user/type"
// import type { RouteObject } from "@/router/type"
// 引入存储方法
import { getItem, setItem, removeItem } from "@/utils/storage"
/* interface IThunkState {
	state: RootState
} */

interface Istate {
	token: string
	userInfo: UserInfo | null
	dynamicRouteList: string
}

const initialState: Istate = {
	token: getItem("token") || "",
	userInfo: JSON.parse(getItem("userInfo")) || null,
	dynamicRouteList: getItem("dynamicRouteList") || "[]",
}

/* export const fetchLogin = createAsyncThunk<void, loginForm, IThunkState>(
	"login",
	(data, { dispatch }) => {
		reqLogIn(data)
			.then((res) => {
				if (res.code === 200) {
					console.log(res.data)
					dispatch(saveTokenAction(res.data))
					dispatch(fetchUserInfo(res.data as any))
				} else {
					throw Error(res?.message)
				}
			})
			.catch((error) => console.dir(error))
	},
)

export const fetchUserInfo = createAsyncThunk<void, string, IThunkState>(
	"userinfo",
	(token, { dispatch }) => {
		token.trim() !== "" &&
			reqUserInfo().then((res) => {
				if (res.code === 200) {
					dispatch(saveUserInfoAction(res.data))
				}
			})
	},
) */

const userSlice = createSlice({
	name: "userStore",
	initialState,
	reducers: {
		saveTokenAction: (state, { payload }) => {
			state.token = payload
			setItem("token", state.token)
		},
		saveUserInfoAction: (state, { payload }) => {
			state.userInfo = payload
			setItem("userInfo", JSON.stringify(state.userInfo))
		},
		saveDynamicRouteListAction: (state, { payload }) => {
			state.dynamicRouteList = payload
			setItem("dynamicRouteList", state.dynamicRouteList)
		},
		clearAction: (state) => {
			state.token = ""
			state.userInfo = null
			state.dynamicRouteList = "[]"
			removeItem("token")
			removeItem("userInfo")
			setItem("dynamicRouteList", state.dynamicRouteList)
		},
	},
})
export const {
	saveTokenAction,
	saveUserInfoAction,
	saveDynamicRouteListAction,
	clearAction,
} = userSlice.actions
export default userSlice.reducer
